package org.aceor.mddal.gateway.merger.orderby;

import org.aceor.mddal.common.sqlparser.result.object.OrderByColumn;
import org.aceor.mddal.gateway.datatype.DataType;
import org.aceor.mddal.gateway.util.DataTypeUtil;
import org.aceor.mddal.gateway.util.ResultSetUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by lxue on 16/4/16.
 */
public class OrderByValue implements Comparable<OrderByValue> {

    private Object value;
    private DataType dataType;
    private OrderByColumn orderByColumn;

    public OrderByValue(List<OrderByColumn> orderByColumns, ResultSet resultSet) throws SQLException {
        //暂时支持单字段排序.忽略第二字段
        orderByColumn = orderByColumns.get(0);
        value = ResultSetUtil.getValue(orderByColumn.getName(), orderByColumn.getAlias(), resultSet);
        dataType = DataTypeUtil.getTypeOfObject(value);
    }

    @Override
    public int compareTo(OrderByValue o) {
        int result = dataType.compare(this.value, o.value);
        return orderByColumn.isAsc() ? result : -result;
    }

    public Object getValue() {
        return value;
    }
}
